﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using SBBitmap;

namespace ImagePreprocessing
{
    public static class ImagePreprocessing
    {
        public enum _Color{Green,Red, Blue};
        public static WarpBitmap Preprocess(WarpBitmap bmp, _Color color, double percent)
        { 
            Color maxColor = GetMaxColor(bmp);
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    double avg = default(double);
                    bool flag = false;
                    Color c = bmp.GetPixel(j, i);
                    
                    switch(color)
                    {
                        case _Color.Red:
                            avg = (c.G + c.B) / 2.0;
                            flag = c.R >= avg + avg * percent;
                            break;
                        case _Color.Green:
                            avg = (c.R + c.B) / 2.0;
                            flag = c.G >= avg + avg * percent;
                            break;
                        case _Color.Blue:
                            avg = (c.G + c.R) / 2.0;
                            flag = c.B >= avg + avg * percent;
                            break;
                        default:
                            //do nothing
                            break;
                    }
                    bmp.SetPixel(j, i, flag ? maxColor : c);
                }
            }
            return bmp;
        }


        public static Color GetMaxColor(WarpBitmap bmp)
        {
            int[] argbHist = new int[256 * 256 * 256];
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    Color c = bmp.GetPixel(j, i);
                    int cValue = c.B + (c.G * 256) + (c.R * (256 * 256));
                    argbHist[cValue]++;
                }
            }

            int currColor = 0;
            int maxCount = 0;
            for (int i = 0; i < argbHist.Length; i++)
            {
                if (argbHist[i] > maxCount)
                {
                    maxCount = argbHist[i];
                    currColor = i;
                }

            }            
            int r = currColor / (256 * 256);
            int rest = currColor - (r * 256 * 256);
            int g = rest / 256;
            int b = rest - (g * 256);
            
            return Color.FromArgb(r,g,b);
        }
    }
}
